package com.hackafone.tale.service.dao;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import javax.persistence.EntityManager;

import com.hackafone.tale.service.model.Tail;
import com.hackafone.tale.service.model.Tale;

public enum TailDao
{
	INSTANCE;

	public List<Tail> listTails(long taleID)
	{
		EntityManager em = EMFService.get().createEntityManager();

		Query q = em
				.createQuery("select t from Tail t where t.taleId = :taleId");
		q.setParameter("taleId", taleID);
		List<Tail> tails = q.getResultList();
		
		Collections.sort(tails, new Comparator<Tail>()
		{

			@Override
			public int compare(Tail o1, Tail o2)
			{
				
				if( o1.getIndex() == o2.getIndex())
					return 0;
				else if(o1.getIndex() > o2.getIndex())
					return 1;
				else
					return -1;
			}
			});
		
		
		return tails;
	}

	public void add(Tail tail)
	{
		synchronized (this)
		{
			Tale tale = TaleDao.INSTANCE.getTaleById(tail.getTale());
			
			
			tail.setIndex(tale.getCurrentInteractions());
			tale.setCurrentInteractions((tale.getCurrentInteractions() + 1));
			tale.setLastCountry(tail.getCountry());
			tale.setLastCity(tail.getCity());
			tale.setLastLat(tail.getLat());
			tale.setLastLon(tail.getLon());
			
			EntityManager em = EMFService.get().createEntityManager();
			em.persist(tail);
			em.close();
			
			
			EntityManager em1 = EMFService.get().createEntityManager();
			em1.persist(tale);
			em1.close();
		}
	}

	public Tail getTailById(long tailId)
	{

		EntityManager em = EMFService.get().createEntityManager();
		try
		{
			Tail tail = em.find(Tail.class, tailId);
			return tail;
		}
		finally
		{
			em.close();
		}
	}

	// public List<Todo> getTodos(String userId) {
	// EntityManager em = EMFService.get().createEntityManager();
	// Query q = em
	// .createQuery("select t from Todo t where t.author = :userId");
	// q.setParameter("userId", userId);
	// List<Todo> todos = q.getResultList();
	// return todos;
	// }
	//
	// public void remove(long id) {
	// EntityManager em = EMFService.get().createEntityManager();
	// try {
	// Todo todo = em.find(Todo.class, id);
	// em.remove(todo);
	// } finally {
	// em.close();
	// }
	// }

}
